package org.agile.grenoble.client;


import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import org.agile.grenoble.data.IUserStorage;
import org.agile.grenoble.user.User;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class GetOrCreateUserClient {

	
	public User getorCreateUser(String userName, String email) {
		
		Client c = Client.create();
		c.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
		System.out.println("Client created, going to create a webresource") ;
		StringBuffer url =  new StringBuffer("http://localhost:9998/");
		
		WebResource r = c.resource(url.toString());
		MultivaluedMap<String, String> params = new MultivaluedMapImpl();
		params.add("username", userName);
		params.add("email", email);

		WebResource resource = r.path("addUser").queryParams(params);

		System.out.println("WebResource created, getting the answer");
		Builder builder = resource.accept(MediaType.APPLICATION_JSON_TYPE,MediaType.TEXT_PLAIN_TYPE) ;
		Builder b1 = builder.header("X-FOO", "BAR");
		String response = b1.get(String.class);
		
		
		System.out.println("Response is :" + response ) ;
		
		User newUser = new User();
		
		if (response == null || response.equals(""))
		{
			newUser = null;
		}
		else
		{	
			int UserId = -1;
			try 
			{
				UserId = Integer.parseInt(response.trim());
			}
			catch (Exception e)
			{
				System.out.println("UserId not valid" + e.getMessage());
			}
			
			newUser.setName(userName);
			newUser.setEmail(email);
			newUser.setId(UserId);
		}
		return newUser;
	}

	
}